package com.sansecy.pagesnaprecyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.FrameLayout;

/**
 * 2018/4/18
 * Created by gaohanyu.
 */

public class CornerFrameLayout extends FrameLayout {
    private static final float DEFAULT_CORNER_SIZE = 15;
    private Path roundPath;
    private float cornerSize = DEFAULT_CORNER_SIZE;

    public CornerFrameLayout(@NonNull Context context) {
        super(context);
    }

    public CornerFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initFromAttributes(context, attrs);
    }

    public CornerFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initFromAttributes(context, attrs);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        if (roundPath == null) {
            roundPath = new Path();
            roundPath.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerSize, cornerSize, Path.Direction.CW);
        }
        canvas.clipPath(roundPath);
        super.dispatchDraw(canvas);
    }

    private void initFromAttributes(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CornerFrameLayout);
        try {
            cornerSize = a.getDimension(R.styleable.CornerFrameLayout_cornerSize, DEFAULT_CORNER_SIZE);
        } finally {
            a.recycle();
        }
    }

    public void setCornerSize(float cornerSize) {
        if (!(this.cornerSize == cornerSize)) {
            this.cornerSize = cornerSize;
            requestLayout();
        }
    }
}
